package com.leaf.spring.y201906.day25.arithmetic.round;

import java.util.HashMap;
import java.util.Map;

import com.leaf.spring.y201906.day25.arithmetic.ServerIps;

/**
 * 平滑加权轮询
 * 
 * @Title:
 * @Description:
 * @Author: leaf
 * @Since:2019年6月26日
 * @Version:1.2.0
 */
public class WeightRoundRobinArithV2 {

	private static Map<String, Weight> ips = new HashMap<>();

	public String getServer() {

		// 如果集合为空，则读取服务列表，加入新集合
		if (ips.isEmpty()) {
			ServerIps.WEIGHT_LIST.forEach((key, value) -> {
				ips.put(key, new Weight(key, value, value));
			});
		}

		// 找出weight最大值
		Weight maxWeight = null;
		for (Weight weight : ips.values()) {
			if (maxWeight == null || weight.getCurrentWeight() > maxWeight.getCurrentWeight()) {
				maxWeight = weight;
			}
		}

		// 将max减去总权重和
		int totalWeight = ServerIps.WEIGHT_LIST.values().stream().reduce(0, (w1, w2) -> w1 + w2);
		maxWeight.setCurrentWeight(maxWeight.getCurrentWeight() - totalWeight);

		// 所有的服务当前权重统一加上原始权重
		ips.values().forEach(weight -> weight.setCurrentWeight(weight.getCurrentWeight() + weight.getWeight()));

		// 返回最大动态权重服务
		return maxWeight.getIp();
	}

	public static void main(String[] args) {

		for (int i = 0; i < 20; i++) {
			WeightRoundRobinArithV2 arithV2 = new WeightRoundRobinArithV2();
			System.out.println(arithV2.getServer());
		}

	}

}
